/*
 * @Author: SamZhang samzhang@apjcorp.com
 * @Date: 2022-12-02 10:14:44
 * @LastEditors: SamZhang samzhang@apjcorp.com
 * @LastEditTime: 2023-02-16 15:16:00
 * @FilePath: /circulation-web/src/components/StorageServices.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import EditableConfigList, {
  EditableConfigListStateProps,
  EditableConfigListDispatchProps,
  EditableConfigListOwnProps,
} from "./EditableConfigList";
import { connect } from "react-redux";
import ActionCreator from "../actions";
import { StorageServicesData, StorageServiceData } from "../interfaces";
import ServiceEditForm from "./ServiceEditForm";

const applocation_root = localStorage.getItem("MOBEBR_CONFIG_APPLICATION_ROOT");
/** Right panel for storage services on the system configuration page. */
export class StorageServices extends EditableConfigList<
  StorageServicesData,
  StorageServiceData
> {
  EditForm = ServiceEditForm;
  listDataKey = "storage_services";
  itemTypeName = "storage service";
  urlBase = applocation_root + "/admin/web/config/storage/";
  identifierKey = "id";
  labelKey = "protocol";

  label(item): string {
    for (const protocol of this.props.data.protocols) {
      if (protocol.name === item.protocol) {
        return `${item.name}: ${protocol.label}`;
      }
    }
    return item.protocol;
  }
}

function mapStateToProps(state, ownProps) {
  const data = Object.assign(
    {},
    (state.editor.storageServices && state.editor.storageServices.data) || {}
  );
  // fetchError = an error involving loading the list of storage services; formError = an error upon
  // submission of the create/edit form.
  return {
    data: data,
    responseBody:
      state.editor.storageServices &&
      state.editor.storageServices.successMessage,
    fetchError: state.editor.storageServices.fetchError,
    formError: state.editor.storageServices.formError,
    isFetching:
      state.editor.storageServices.isFetching ||
      state.editor.storageServices.isEditing,
  };
}

function mapDispatchToProps(dispatch, ownProps) {
  const actions = new ActionCreator(null, ownProps.csrfToken);
  return {
    fetchData: () => dispatch(actions.fetchStorageServices()),
    editItem: (data: FormData) => dispatch(actions.editStorageService(data)),
    deleteItem: (identifier: string | number) =>
      dispatch(actions.deleteStorageService(identifier)),
  };
}

const ConnectedStorageServices = connect<
  EditableConfigListStateProps<StorageServicesData>,
  EditableConfigListDispatchProps<StorageServicesData>,
  EditableConfigListOwnProps
>(
  mapStateToProps,
  mapDispatchToProps
)(StorageServices);

export default ConnectedStorageServices;
